/**
 * @(#)DbConfig.java, 2013年10月28日. Copyright 2012 Yodao, Inc.
 *                                     All rights reserved. YODAO
 *                                     PROPRIETARY/CONFIDENTIAL. Use is subject
 *                                     to license terms.
 */
package com.scitc.pleasurevideo.datasql;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * @author contradiction 对数据库访问的一个简单封装
 */
public class DbContext {

	private SQLiteDatabase db;

	public DbContext(SQLiteDatabase db) {
		this.db = db;
	}

	public List<String[]> queryList(String sql, String[] selectionArgs) {
		return query(sql,selectionArgs);
	}
	public List<String[]> queryList(String sql) {
		String[] selectionArgs=new String[0];
		return query(sql,selectionArgs);
	}

	private List<String[]> query(String sql, String[] selectionArgs){
		List<String[]> list = new ArrayList<String[]>();
		if (db.isOpen()) {
			Cursor cursor = db.rawQuery(sql, selectionArgs);
			int columnCount = cursor.getColumnCount();
			while (cursor.moveToNext()) {
				String[] items = new String[columnCount];
				int i = 0;
				while (i < columnCount) {
					items[i] = cursor.getString(i);
					i++;
				}
				list.add(items);
			}
			cursor.close();
			db.close();
		}
		return list;
	}

	public String queryUnique(String sql, String[] selectionArgs) {
		String result = "";
		if (db.isOpen()) {
			Cursor cursor = db.rawQuery(sql, selectionArgs);
			if (cursor.moveToNext()) {
				result = cursor.getString(0);
			}
			cursor.close();
			db.close();
		}
		return result;
	}
	
	public void execSQL(String sql){
		if (db.isOpen()) {
			db.execSQL(sql);
		}
	}

	public void executeSQL(String sql, String[] bindArgs) {
		if (db.isOpen()) {
			db.execSQL(sql, bindArgs); 
			db.close();
		}
	}

	public SQLiteDatabase getDb() {
		return db;
	}

	public void setDb(SQLiteDatabase db) {
		this.db = db;
	}

}
